package com.vonchenchen.usbmuxd_android.usbmuxd.muxdprotocol;

import android.content.Context;
import android.hardware.usb.UsbAccessory;
import android.util.Log;

import com.vonchenchen.usbmuxd_android.usbmuxd.Config;
import com.vonchenchen.usbmuxd_android.usbmuxd.usb.OnUSBConnStatusChanged;
import com.vonchenchen.usbmuxd_android.usbmuxd.usb.USBHelper;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

/**
 * 数据通信协议封装类，本例中只涉及简单usb层传输，并没有封装上层协议
 * Created by lidechen on 2/25/17.
 */

public class DataEngine implements ISimpleTcpManager {
    private static final String TAG = DataEngine.class.getSimpleName();
    private Context mContext;
    /**
     * 数据通信对象引用
     */
    private USBHelper mConmunicateHelper;

    public interface Listener{
        void onConnected();
        void onDisconnected();
    }
    private Listener _listener;
    public DataEngine(Context context) {
        mContext = context;
        mConmunicateHelper = new USBHelper(mContext);
    }
    public void registerListener(Listener listener){
        this._listener=listener;
    }
    public void start() {
        //数据传输层准备就绪 可以开启数据收发任务
        mConmunicateHelper.setOnDataTranPrepared(new USBHelper.OnDataTranPrepared() {
            @Override
            public void onDataTranPrepared(FileInputStream inputStream, FileOutputStream outputStream) {
                if (Config.DEBUG) {
                    Log.i(TAG, "accessory opened: inputStream " + inputStream + " outputStream " + outputStream);
                }
            }
        });
    }

    public void openUSBAsync(boolean reset) {
        mConmunicateHelper.openAsync(new OnUSBConnStatusChanged() {
            @Override
            public void onUSBConnect(UsbAccessory accessory) {
                Log.d(TAG,"onUSBConnect "+accessory);
                if(_listener!=null){
                    _listener.onConnected();
                }
            }

            @Override
            public void onUSBConnectFailed(UsbAccessory accessory) {
                Log.i(TAG, "onUSBConnectFailed "+accessory);
                mConmunicateHelper.close();
                if(_listener!=null){
                    _listener.onDisconnected();
                }
            }

            @Override
            public void onUSBDisconnect(UsbAccessory accessory) {
                Log.i(TAG, "onUSBDisconnect "+accessory);
                mConmunicateHelper.close();
                if(_listener!=null){
                    _listener.onDisconnected();
                }
            }
        });
    }

    public void closeUSB() {
        mConmunicateHelper.close();
    }

    @Override
    public int readTcpData(byte[] data) {
        return mConmunicateHelper.readSyncFromUSB(data);
    }

    @Override
    public int writeRawData(byte[] data) {
        return mConmunicateHelper.writeSyncToUSB(data);
    }

}
